/*
 * 
 * Version 1.00
 * 
 * Created on 2007-6-4
 * Encoding GB2312
 */
package net.comm.friend.service.impl;

import java.sql.Connection;
import java.util.List;

import net.comm.common.Email;
import net.comm.common.GlbFinal;
import net.comm.common.ReturnMessage;
import net.comm.common.common;
import net.comm.db.DBProcException;


import net.comm.encrypt.DesEncrypt;
import net.comm.friend.bean.BaseInvite;
import net.comm.friend.db.DbInviteService;
import net.comm.friend.db.InviteServiceSqlMysql;
import net.comm.friend.web.form.InviteForm;
import net.comm.page.PageCtr;
import net.comm.param.service.impl.SequenceMgr;

import net.comm.user.bean.BaseUsers;
import net.comm.user.db.DbUsersService;
import net.comm.user.db.UsersServiceSqlMysql;
import net.comm.user.service.impl.UserSysinfoServiceImpl;
import net.comm.user.web.form.UserSysinfoForm;
import net.comm.util.DatetimeUtil;
import net.comm.util.DbcpPool;

import org.apache.log4j.Logger;
import org.sakaiproject.db.impl.BasicSqlService;


/**
 *
 * @author hcgong(hcgong@sina.com)
 * @version 1.0
 * @date 2007-6-4
 */
public class InviteServiceImpl {

	static Logger logger = Logger.getLogger(InviteServiceImpl.class.getName());

	/**
	 * 
	 * @see net.IUserbasicService.module.other.IUserService
	 * 		#list(net.swift.module.other.ExaQueryBean, net.swift.common.ReturnMessage)
	 */
	public List list(InviteForm theForm,  ReturnMessage msg) 
	{
		List list = null;

		Connection cn = null;

		try
		{
			cn = DbcpPool.getConnection();
			
			InviteServiceSqlMysql servSql = new InviteServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();

			//取得FORM中传入的查询参数
			Object[] fields2 = new Object[1];
			
			fields2[0] = theForm.getInvitorID();

			/*
			 * 获得查询SQL语句
			 */
			String sql = servSql.getCountSql2();

			/**
			 * 根据SQL执行结果计算分页相关信息
			 */
			PageCtr page = theForm.getPage();
			page.setTotalNum(bSqlServ.dbCount(cn, sql, fields2));
			page.caculate();

			//取得FORM中传入的查询参数
			Object[] fields = new Object[3];
			
			fields[0] = theForm.getInvitorID();
			fields[1] = page.getPos()-1;
			fields[2] = page.getPageSize();
			
			sql = servSql.getRecbyPageSql();

			list = bSqlServ.dbRead(cn, sql, fields, new DbInviteService());
			
			
		    DbcpPool.returnConnection(cn);
		    
		} catch(Exception ex) 
		{
			/**
			 * 记录相关日志
			 */
			logger.error(ex.getMessage());
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
			
		} finally {
			DbcpPool.returnConnection(cn);
		}		
		
		return list;
	}

	/**
	 * 返回根据会员ID查询的会员好友
	 */
	public List list(String  userID) 
	{
		List list = null;
		Connection cn = null;

		try
		{
			cn = DbcpPool.getConnection();
			
			//取得FORM中传入的查询参数
			Object[] fields = new Object[1];
			
			fields[0] = userID;			

			InviteServiceSqlMysql servSql = new InviteServiceSqlMysql();
						
			BasicSqlService  bSqlServ = new BasicSqlService();

			/*
			 * 获得查询SQL语句
			 */
			String sql = servSql.getByUserIDSql();
									
			list = bSqlServ.dbRead(cn, sql, fields, new DbInviteService());
									
		    DbcpPool.returnConnection(cn);
		    
		} catch(Exception ex) 
		{
			/**
			 * 记录相关日志
			 */
			logger.error(ex.getMessage());
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}		
			
		} finally {
			DbcpPool.returnConnection(cn);
		}
		
		return list;
	}
	
	/**
	 * @see net.IUserbasicService.module.other.IUserService
	 * 		#get(net.swift.db.tab_paramnostro, net.swift.common.ReturnMessage)
	 */
	public void get(InviteForm theForm, ReturnMessage msg) 
	{
		Connection cn = null;
		try
		{
			cn = DbcpPool.getConnection();
			List list = null;

			//取得FORM中传入的查询参数
			Object[] fields = new Object[1];
			
			fields[0] = theForm.getSeqID();			
			
			InviteServiceSqlMysql servSql = new InviteServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();
			
			String sql = servSql.getbykeySql();			
					
			list = bSqlServ.dbRead(cn, sql, fields, new DbInviteService());
			
			if(list.size() ==0){
				common.setAppFailMsg(msg , " 取记录失败，请检查！");
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;				
			}
			
			BaseInvite base = (BaseInvite)list.get(0);
				
			theForm.setSeqID(base.getSeqID());
			theForm.setInvitorID(base.getInvitorID());
			theForm.setInvitepath(base.getInvitepath());
			theForm.setUserID(base.getUserID());
			theForm.setAddmode(base.getAddmode());
			theForm.setStatus(base.getStatus());
			theForm.setMTime(base.getMTime());
			
			DbcpPool.returnConnection(cn);
			return;
			
		} catch(Exception ex) 
		{
			logger.error("System error , param get about invite" + ex);
			common.setAppFailMsg(msg , ex.getMessage());
			try 
			{
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
		} finally {
			DbcpPool.returnConnection(cn);
		}
		
		return ;
	}
	/**
	 * 添加会员邀请到表中
	 * @see net.IUserbasicService.module.other.IUserService#add(net.swift.common.ReturnMessage)
	 */
	public void add( Connection cn, BaseInvite base, ReturnMessage msg) 
	{
	
		try
		{
			//取得FORM中传入的查询参数
			Object[] fields = new Object[7];
			
			fields[0] = SequenceMgr.generateSeq(GlbFinal.SEQ_INITDATE, GlbFinal.SEQ_INVITEID);			
			fields[1] = base.getInvitorID();
			fields[2] = base.getInvitepath();
			fields[3] = base.getUserID();
			fields[4] = base.getAddmode();
			fields[5] = base.getStatus();
			fields[6] = DatetimeUtil.getDatetime();
			
			InviteServiceSqlMysql servSql = new InviteServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();
			
			String sql = servSql.getInsertSql();
						
			boolean  res = bSqlServ.dbWrite(cn, sql, fields);
			if(!res){
				common.setAppFailMsg(msg , " 添加好友失败！");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return ;
			}

		} catch(Exception ex) 
		{
			common.setAppFailMsg(msg , " 添加好友失败！");
			logger.error("System error , param get about operlog" + ex);
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
		}
		
		return ;
	}
	/**
	 * 修改邀请状态到表中
	 * @see net.IUserbasicService.module.other.IUserService#add(net.swift.common.ReturnMessage)
	 */
	public void updsts( Connection cn, String userID, ReturnMessage msg) 
	{
	
		try
		{

			//取得FORM中传入的查询参数
			Object[] fields = new Object[1];
			
			fields[0] = userID;			
			
			InviteServiceSqlMysql servSql = new InviteServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();
			
			String sql = servSql.getByUserIDSql();
						
			List list = bSqlServ.dbRead(cn, sql, fields, new DbInviteService());
			
			if(list.size() ==0){
				return;	//不是邀请的好友			
			}
			
			BaseInvite base = (BaseInvite)list.get(0);
				
			Object[] fields2 = new Object[7];
			
			fields2[0] = base.getInvitorID();
			fields2[1] = base.getInvitepath();
			fields2[2] = base.getUserID();
			fields2[3] = base.getAddmode();
			fields2[4] = GlbFinal.STS_NORMAL;
			fields2[5] = DatetimeUtil.getDatetime();
			fields2[6] = base.getSeqID();			
			
			sql = servSql.getUpdateSql();
						
			boolean  res = bSqlServ.dbWrite(cn, sql, fields2);
			if(!res){
				common.setAppFailMsg(msg , " 更新状态失败！");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return ;
			}	
			//邀请人增加积分， 增加五分
			UserSysinfoServiceImpl syservice  = new UserSysinfoServiceImpl();
			UserSysinfoForm sysForm = new UserSysinfoForm();
			sysForm.setUserID(base.getInvitorID());
			sysForm.setIntegral(5);

			syservice.update(cn, sysForm, msg);
			if(msg.getErrCode() != 0){
				common.setAppFailMsg(msg , " 更新积分失败！");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;
			}				

		} catch(Exception ex) 
		{
			common.setAppFailMsg(msg , " 更新状态失败！");
			logger.error("System error , param get about operlog" + ex);
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
		}
		
		return ;
	}
	/**
	 * 删除一条指定记录
	 * @see net.IUserbasicService.module.other.IUserService#update(net.swift.common.ReturnMessage)
	 */
	public void delete(InviteForm theForm, ReturnMessage msg) 
	{
		
		Connection cn = null;
		try
		{
			cn = DbcpPool.getConnection();
			
			DbcpPool.beginTran(cn);

			//取得FORM中传入的查询参数
			Object[] fields = new Object[1];
			
			fields[1] = theForm.getSeqID();
			
			InviteServiceSqlMysql servSql = new InviteServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();
			String sql = servSql.getDeleteSql();
			
								
			boolean  res = bSqlServ.dbWrite(cn, sql, fields);
			if(res){
				common.setAppFailMsg(msg , " 更新记录失败，请检查！");
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;
			}
			
			DbcpPool.returnConnection(cn);
			return;
			
		} catch(Exception ex) 
		{
			logger.error("System error , param get about invite" + ex);
			common.setAppFailMsg(msg , ex.getMessage());
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}			
		} finally {
			DbcpPool.returnConnection(cn);
		}
		
		return ;
	}
	
	/**
	 * 产生邀请链接
	 * @see net.IUserbasicService.module.other.IUserService#add(net.swift.common.ReturnMessage)
	 */
	public void geninvite(InviteForm theForm, ReturnMessage msg) 
	{
		try
		{
			
		
			DesEncrypt des = new DesEncrypt(); //实例化一个对像 
			
			des.getKey("aadd.fcwrw"); 			//生成密匙 
			
			String strEnc = des.getEncString(String.valueOf(theForm.getInvitorID())); //加密字符串,返回String的密文 
			
			StringBuffer sb = new StringBuffer();
			
			sb.append(GlbFinal.WEB_HTTP);
			sb.append(GlbFinal.FOLDER_INSTALL);
			sb.append("/invite.do?action=register&ID=");
			sb.append(strEnc);
			
			theForm.setInviteURL(sb.toString());
						
		} catch(Exception ex) 
		{
			logger.error("System error , param insert about invite" , ex);
			common.setAppFailMsg(msg , ex.getMessage());
		}
		return;
	}

	/**
	 *好友接受邀请注册
	 * @see net.IUserbasicService.module.other.IUserService#add(net.swift.common.ReturnMessage)
	 */
	public void register(InviteForm theForm, ReturnMessage msg) 
	{
		Connection cn = null;
		try
		{
	
			cn = DbcpPool.getConnection();

			DesEncrypt des = new DesEncrypt(); //实例化一个对像 
			
			des.getKey("aadd.fcwrw"); //生成密匙 
			
			String strEnc = des.getDesString(String.valueOf(theForm.getInvitorID())); //解密字符串,返回邀请人ID 
			
			theForm.setInvitorID(Integer.valueOf(strEnc));		//邀请人ID
			
			//判断邀请人是否存在
			Object[] fields = new Object[1];
			
			fields[0] = strEnc;
						
			UsersServiceSqlMysql servSql = new UsersServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();
			
			String sql = servSql.getbykeySql();
			
			List list = bSqlServ.dbRead(cn, sql, fields, new DbUsersService());
			if(list.size() == 0){
				common.setAppFailMsg(msg , "邀请人信息错误,请重新邀请");
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;				
			}			
			
			DbcpPool.returnConnection(cn);
			return;

			
		} catch(Exception ex) 
		{
			logger.error("System error , param insert about invite" , ex);
			common.setAppFailMsg(msg , ex.getMessage());
			try 
			{
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
			} catch(Exception ex1) 
			{
				ex1.printStackTrace();
				logger.error("事务回滚操作失败!ExaServiceImpl->add(01)" , ex1);
			}		
		} finally {
			DbcpPool.returnConnection(cn);
		} 
		return;
	}	

	/**
	 * @see net.IUserbasicService.module.other.IUserService
	 * 		#get(net.swift.db.tab_paramnostro, net.swift.common.ReturnMessage)
	 */
	public void email(InviteForm theForm, ReturnMessage msg) 
	{
		Connection cn = null;
		try
		{
	
			cn = DbcpPool.getConnection();
			
			//取得FORM中传入的查询参数
			Object[] fields = new Object[1];
			
			fields[0] = theForm.getInvitorID();
						
			UsersServiceSqlMysql servSql = new UsersServiceSqlMysql();
			
			String sql = servSql.getbykeySql();
			
			BasicSqlService  bSqlServ = new BasicSqlService();
						
			List list = bSqlServ.dbRead(cn, sql, fields, new DbUsersService());
			
			if(list.size() == 0){
				common.setAppFailMsg(msg , "邀请人信息错误,请重新邀请");
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;				
			}
			BaseUsers base = (BaseUsers)list.get(0);	
			
			
			
			Email themail = new Email(GlbFinal.EMAIL_SMTP);  
			StringBuffer emailcont = new StringBuffer("");

			themail.setNeedAuth(true);  
		    themail.setSubject("人力资源职业开发评价公共服务平台(www.gdosta.org.cn)：欢迎你的加入");  //题目
		    themail.setFrom(GlbFinal.EMAIL_ADDR,GlbFinal.EMAIL_FRNAME);//发件人
		    themail.setNamePass(GlbFinal.EMAIL_FRUSER,GlbFinal.EMAIL_FRUSERPSD);//用户、密码  

		    emailcont.delete(0, emailcont.length());
			emailcont.append("你好:<br>");
			emailcont.append(base.getNick());
			emailcont.append("邀请您加入人力资源职业开发公共服务平台，点击该链接注册:" +
					theForm.getInviteURL() +
					"&nbsp; <a href='" +
					theForm.getInviteURL() +
					"' target='_blank'>注册</a><br><br>");
			emailcont.append("<a href='" + GlbFinal.WEB_HTTP +
					"' target='_blank'>" +
					"人力资源职业开发公共服务平台</a><br>");
			emailcont.append("“人力资源职业开发评价公共服务平台”由广东省职业技能鉴定指导中心建设的服务平台，" +
					"具有集职业能力需求调查与分析、职业能力评价和职业能力开发应用“三位 一体”的人力资源职业能力" +
					"开发评价公共服务平台。<br>" +
					"网址：http://www.gdosta.org.cn<br>");
		    themail.setBody(emailcont.toString());  //发送内容
			//调用email类，发送邮件
		    
		    String[] emailArr = theForm.getEmail().split(" ");
		    
		    if(emailArr.length > 0){
		    	
		    	int len = emailArr.length;
		    	for(int i=0; i<len; i++){
		    		
				    themail.setTo(emailArr[i]);  //收件人
				    themail.sendout();  	
		    	}
		    }
			DbcpPool.returnConnection(cn);
			return;
			
		} catch(DBProcException ex) 
		{
			logger.error("Running sql error , param get about invite" + ex);
			common.setDbErrorMsg(msg , "ExaServiceImpl->get" , ex.getMessage() , ex.getErrorCode());
		} catch(Exception ex) 
		{
			logger.error("System error , param get about invite" + ex);
			common.setAppFailMsg(msg , ex.getMessage());
		} finally {
			DbcpPool.returnConnection(cn);
		}
		
		return ;
	}	
	
	/**
	 * 更新一条指定记录
	 * @see net.IUserbasicService.module.other.IUserService#update(net.swift.common.ReturnMessage)
	 */
	public void update(InviteForm theForm, ReturnMessage msg) 
	{
		

				
		return ;
	}

}
